<template>
  <div class="page-content feedback-create">
    <!-- 页面标题和说明 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold">意见反馈</h1>
      <p class="text-gray-500 mt-2">欢迎提供您的宝贵意见和建议，帮助我们改进系统</p>
    </div>

    <!-- 反馈表单卡片 -->
    <el-card shadow="hover">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        status-icon
        require-asterisk-position="right"
        scroll-to-error
      >
        <el-form-item label="反馈类型" prop="type">
          <div class="feedback-type-selector">
            <el-radio-group v-model="form.type" class="flex flex-wrap gap-3">
              <el-radio-button
                v-for="(value, key) in FeedbackTypeEnum"
                :key="key"
                :label="value"
                class="feedback-type-item border-l-2 border-l-gray-200"
              >
                <div class="flex flex-col items-center p-2 m-2">
                  <i :class="getTypeIcon(value)" class="text-2xl mb-1"></i>
                  <span>{{ value }}</span>
                </div>
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的建议、问题或反馈内容，以便我们更好地了解和处理..."
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="相关截图或图片">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :limit="5"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
          >
            <i class="i-carbon-add text-2xl"></i>
            <div class="mt-1 text-xs text-gray-500">点击上传</div>
            <template #tip>
              <div class="el-upload__tip"> 支持JPG/PNG格式，单张不超过5MB，最多上传5张 </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="联系方式" prop="contactInfo">
          <el-input
            v-model="form.contactInfo"
            placeholder="请留下您的手机号或邮箱，方便我们联系您"
            maxlength="50"
          />
        </el-form-item>

        <el-divider />

        <div class="flex justify-center mt-6">
          <el-button @click="goBack" class="mr-4">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitForm"> 提交反馈 </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 提交结果对话框 -->
    <el-dialog
      v-model="submitSuccessDialogVisible"
      title="提交成功"
      width="400px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="flex flex-col items-center">
        <el-icon class="text-5xl text-green-500 mb-4"><CircleCheck /></el-icon>
        <div class="text-xl font-medium mb-2">感谢您的反馈!</div>
        <div class="text-gray-500 mb-6 text-center">
          我们已收到您的宝贵意见，将尽快处理并回复。
        </div>
        <el-button type="primary" @click="handleSuccess">返回列表</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, FormInstance } from 'element-plus'
  import { CircleCheck } from '@element-plus/icons-vue'
  import { FeedbackTypeEnum } from '@/types/feedback'
  import {
    scenicComplaintFeedbackSaveComplaintFeedbackUsingPost,
    ossSaveMinioFileAsyncUsingPost
  } from '@/api/4a'

  const router = useRouter()
  const formRef = ref<FormInstance>()
  const submitting = ref(false)
  const submitSuccessDialogVisible = ref(false)
  const fileList = ref<any[]>([])

  // 表单数据
  const form = reactive({
    type: FeedbackTypeEnum.SUGGESTION,
    content: '',
    contactInfo: '',
    images: [] as string[]
  })

  // 反馈类型映射
  const FeedbackTypeMap = {
    [FeedbackTypeEnum.BUG]: 1,
    [FeedbackTypeEnum.SUGGESTION]: 2,
    [FeedbackTypeEnum.COMPLAINT]: 3,
    [FeedbackTypeEnum.QUESTION]: 4,
    [FeedbackTypeEnum.OTHER]: 5
  }
  // 表单验证规则
  const rules = {
    type: [{ required: true, message: '请选择反馈类型', trigger: 'change' }],
    content: [
      { required: true, message: '请输入反馈内容', trigger: 'blur' },
      { min: 10, max: 1000, message: '反馈内容长度在10到1000个字符之间', trigger: 'blur' }
    ],
    contactInfo: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$|^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        message: '请输入正确的手机号或邮箱',
        trigger: 'blur'
      }
    ]
  }

  // 获取反馈类型对应的图标
  const getTypeIcon = (type: string) => {
    switch (type) {
      case FeedbackTypeEnum.BUG:
        return 'i-carbon-idea text-red-500'
      case FeedbackTypeEnum.SUGGESTION:
        return 'i-carbon-idea text-green-500'
      case FeedbackTypeEnum.COMPLAINT:
        return 'i-carbon-warning-alt text-yellow-500'
      case FeedbackTypeEnum.QUESTION:
        return 'i-carbon-help text-blue-500'
      case FeedbackTypeEnum.OTHER:
        return 'i-carbon-document text-gray-500'
      default:
        return 'i-carbon-document'
    }
  }

  // 文件上传前检查
  const beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt5M = file.size / 1024 / 1024 < 5

    if (!isJPG && !isPNG) {
      ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
      return false
    }
    if (!isLt5M) {
      ElMessage.error('上传图片大小不能超过 5MB!')
      return false
    }
    return true
  }

  // 文件变更处理
  const handleFileChange = (file: any) => {
    if (fileList.value.length > 5) {
      fileList.value.pop()
      ElMessage.warning('最多只能上传5张图片')
      return
    }

    // 实际项目中，这里应该上传到服务器并获取URL
    if (file.raw) {
      const reader = new FileReader()
      reader.onload = (e: any) => {
        const index = fileList.value.findIndex((item) => item.uid === file.uid)
        if (index !== -1) {
          form.images[index] = e.target.result
        } else {
          form.images.push(e.target.result)
        }
      }
      reader.readAsDataURL(file.raw)
    }
  }

  // 移除文件
  const handleFileRemove = (file: any) => {
    const index = fileList.value.findIndex((item) => item.uid === file.uid)
    if (index !== -1) {
      form.images.splice(index, 1)
    }
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return
    await formRef.value.validate().then(async (valid) => {
      if (valid) {
        submitting.value = true

        try {

          const filePages: Array<Promise<any>> = []
          // 上传图片
          fileList.value.forEach((image) => {
            filePages.push(
              ossSaveMinioFileAsyncUsingPost({
                body: { file: image.raw }
              })
            )
          })
          let fileUrls: string[] = []
          const result = await Promise.all(filePages)
          result.forEach((res) => {
            if (res.code === 0) {
              fileUrls.push(res.data.path)
            } else {
              ElMessage.error(res.msg || `图片${res.data.name}上传失败`)
              submitting.value = false
            }
          })

          let body = {
            type: FeedbackTypeMap[form.type],
            file: fileUrls.join(','),
            content: form.content,
            contactWay: form.contactInfo,
            visitorUserId: 1003,
            source: 1,
            state: 1,
            current: 1,
            size: 10
          }
          scenicComplaintFeedbackSaveComplaintFeedbackUsingPost({ body }).then((res) => {
            if (res.code === 0) {
              submitting.value = false
              submitSuccessDialogVisible.value = true
            } else {
              ElMessage.error(res.msg || '提交失败')
              submitting.value = false
            }
          })
        } catch (error) {
          console.error('提交反馈失败', error)
          ElMessage.error('提交失败，请稍后重试')
          submitting.value = false
        }
      } else {
        ElMessage.warning('请完善表单信息')
        return false
      }
    })
  }

  // 处理提交成功
  const handleSuccess = () => {
    submitSuccessDialogVisible.value = false
    router.push('/feedback/FeedbackList')
  }

  // 返回
  const goBack = () => {
    router.push('/feedback/FeedbackList')
  }
</script>

<style lang="scss" scoped>
  .feedback-create {
    .feedback-type-selector {
      .el-radio-button {
        margin-right: 10px;
        margin-bottom: 10px;

        &:deep(.el-radio-button__inner) {
          border-radius: 4px;
          padding: 12px 20px;
          height: auto;
          min-width: 100px;
          border:1px solid rgb(220, 223, 230)
        }
      }
    }

    :deep(.el-upload--picture-card) {
      --el-upload-picture-card-size: 120px;
    }
    :deep(.el-radio-button.is-active .el-radio-button__original-radio:not(:disabled)+.el-radio-button__inner){
      box-shadow:none
    }
  }
</style>
